// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "MotionAnimInfos.h"
#include "TextInfos.h"
#include "Layers/MotionSubtitlesLayerBase.h"
#include "AnimPlayer/MotionSubtitlesAnimPlayer.h"
#include "GameFramework/Actor.h"
#include "MotionSubtitlesActor.generated.h"

UENUM()
enum class ERTBlendMode : uint8
{
	Overlay = 0,
	Masked = 1,
	InvMasked = 2,
};

UCLASS()
class MOTIONSUBTITLES_API AMotionSubtitlesActor : public AActor
{
	GENERATED_BODY()

protected:
	// 动态字幕屏幕显示区域
	UPROPERTY(EditDefaultsOnly, Category=MotionSubtitles)
	FUint32Vector2 ViewSize;
	
	UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category=MotionSubtitles)
	ERTBlendMode RTBlendMode = ERTBlendMode::Overlay;

	UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category=MotionSubtitles)
	TArray<FMotionAnimInfo> EnterAnimations;

	UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category=MotionSubtitles)
	TArray<FMotionAnimInfo> StayAnimations;

	UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category=MotionSubtitles)
	TArray<FMotionAnimInfo> ExitAnimations;

	UPROPERTY(EditDefaultsOnly, Category=MotionSubtitles)
	TMap<ERTBlendMode, UMaterial*> BlendingMaterials;

	UPROPERTY(EditDefaultsOnly, Category=MotionSubtitles)
	UMaterial* PostProcessMaterial;

	UPROPERTY(VisibleInstanceOnly,Category=MotionSubtitles)
	TArray<TObjectPtr<UTextureRenderTarget2D>> OutputRTs;

	UPROPERTY(VisibleInstanceOnly, Category=MotionSubtitles)
	TMap<ERTBlendMode, TObjectPtr<UMaterialInstanceDynamic>> BlendingMaterialInstances;

	UPROPERTY(VisibleInstanceOnly, Category=MotionSubtitles)
	TObjectPtr<UMaterialInstanceDynamic> PostProcessMaterialInstance;

	UPROPERTY(VisibleInstanceOnly,Category=MotionSubtitles)
	int RTIndex;
	
	TSharedPtr<FMotionSubtitlesAnimPlayer> AnimPlayer;

	TArray<TWeakObjectPtr<UMotionSubtitlesLayerBase>> MotionSubtitlesLayers;

public:
	
	AMotionSubtitlesActor();

protected:
	
	virtual void Tick(float DeltaTime) override;

public:
	UFUNCTION(BlueprintCallable)
	UTextureRenderTarget2D* GetOutput() const;

	TWeakObjectPtr<UMaterialInstanceDynamic> GetPostProcessMaterial() const;
	
	TArray<TWeakObjectPtr<UMotionSubtitlesLayerBase>> GetLayers() const;

	UFUNCTION(BlueprintCallable)
	void ShowText(const FSubtitleParams& Params);

	UFUNCTION(BlueprintCallable)
	void HideText();

private:

	void Initialize();

	void DeInitialize();
	
	void BlendRT(const ERTBlendMode BlendMode, UTextureRenderTarget2D* Foreground, UTextureRenderTarget2D* Background);

	void LoadBlendingMaterials(TMap<ERTBlendMode, TObjectPtr<UMaterialInstanceDynamic>>& Materials);

	void LoadPostProcessMaterial(TObjectPtr<UMaterialInstanceDynamic>& Material);
	
	void LoadSubtitlesLayers(TArray<TWeakObjectPtr<UMotionSubtitlesLayerBase>>& LayerBases) const;
};
